package Tp.caso1;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;



public class Ventana extends Activity {
// 	public static String IP = "10.0.2.2:8080"; //local
//	public static String URL_CENTRAL = "http://" + IP + "/proyecto-utn/comunicacion";
	public static String IP = "176.58.97.39:8080"; 
	public static String URL_CENTRAL = "http://" + IP + "/central/comunicacion";
	LinearLayout lLayout;
	String	idchofer="0";
	String 	idviaje="0";
	String	estadochofer="0";
	String	estadoviaje="2";
	String user;
	String pass;
	String interfaz="no login";

	public static final String BROADCAST_ACTION = "ventana";
	private Intent intent_envio;
	private Intent intent_recibo;
	private final Handler handler = new Handler();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        creacion();
    }
 
    
      public void enviar(View v) //onClick del login(View view) 
          {   
          // escondo el teclado
    	  InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
          imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);  
    	  setInterfaz("login");
          Log.i("ventana", "enviar"); 
          final TextView textViewToChange = (TextView) findViewById(R.id.invalido);
    	  textViewToChange.setText("Login en proceso");
            final EditText userField = (EditText) findViewById(R.id.editText1);  
        	String user = userField.getText().toString();  
 	 	   	final EditText passField = (EditText) findViewById(R.id.editText2);  
        	String pass = passField.getText().toString();   
        	setUser(user);
   	        setPass(pass);
   	        login();
 	     }
   



    void SetViaje(String pasajero,String desde,String hasta)
		{
		final TextView textViewToChange = (TextView) findViewById(R.id.Pasajero);
		textViewToChange.setText(pasajero);
		final TextView textViewToChange2 = (TextView) findViewById(R.id.Desde);
		textViewToChange2.setText(desde);
		final TextView textViewToChange3 = (TextView) findViewById(R.id.Hasta);
		textViewToChange3.setText(hasta);
		final ToggleButton toggle4 = (ToggleButton) findViewById(R.id.LibreOcupado);
		if (!pasajero.equals("Sin viaje asignado")){ 
			toggle4.setChecked(false);
		    this.estadochofer="0";
		    }
		}

    void UnSetViaje()
		{
		final TextView textViewToChange = (TextView) findViewById(R.id.Pasajero);
		textViewToChange.setText("Sin viaje asignado");
		final TextView textViewToChange2 = (TextView) findViewById(R.id.Desde);
		textViewToChange2.setText("");
		final TextView textViewToChange3 = (TextView) findViewById(R.id.Hasta);
		textViewToChange3.setText("");
		final ToggleButton toggle4 = (ToggleButton) findViewById(R.id.LibreOcupado);
		toggle4.setChecked(false);
		this.estadochofer="0";
		}

  public void EstadoViaje(View v) {
		ToggleButton pav = (ToggleButton) findViewById(R.id.PavFv);
		boolean on  = pav.isChecked();
	    if (on) {
	        // pasajero a bordo.
	    	this.estadoviaje="1";
	    } else {
	        //fin de viaje.
	    	this.estadoviaje="2";
			this.UnSetViaje();
        }
	    actualiza();
  }
  
  public void EstadoChofer(View v) {
		ToggleButton libre = (ToggleButton) findViewById(R.id.LibreOcupado);
	    boolean on2 = libre.isChecked();
	    if (on2) {
	        // Taxi libre chofer activo 
	        this.estadochofer="1";
	    } else {
	        // Taxi ocupado 
	        this.estadochofer="0";
	    }
	    actualiza();
  }
  
  private void updateUI(Intent intent) {
	String idviaje = intent.getStringExtra("idviaje"); 
	String pasajero = intent.getStringExtra("pasajero"); 
  	String desde = intent.getStringExtra("desde");
  	String hasta = intent.getStringExtra("hasta");
  	String actualizacion = intent.getStringExtra("actualizacion");
  	String alerta = intent.getStringExtra("alerta");
  	String idchofer = intent.getStringExtra("idchofer");
  	setIdchofer(idchofer);
  	//Log.i("idchofer e interfaz",idchofer+" "+getInterfaz()+" ");
	if (getInterfaz().equals("login"))recepcionlogin();
	else {
	if(getEstado_chofer().contentEquals("1") || pasajero.contentEquals("Sin viaje asignado"))
  			{setIdviaje(idviaje);
            SetViaje(pasajero,desde,hasta);}
  	final TextView textViewToChange5 = (TextView) findViewById(R.id.Ultima);
	textViewToChange5.setText(actualizacion);
	final TextView textViewToChange6 = (TextView) findViewById(R.id.alerta);
	textViewToChange6.setText(alerta);
	}
   }


private Runnable  senUpdatesService = new Runnable() {
	public void run() { 
	    actualiza();    		
	    handler.postDelayed(this, 2000); // 2 seconds
	    }
};

public String getInterfaz() {
	return interfaz;
}

public void setInterfaz(String interfaz) {
	this.interfaz = interfaz;
}

public void actualiza(){		
	Log.d("Ventana", "actualiza");
 	intent_envio.putExtra("user", this.user);
	intent_envio.putExtra("pass", this.pass);
 	intent_envio.putExtra("estadochofer", this.estadochofer);
	intent_envio.putExtra("estadoviaje", this.estadoviaje);
//	intent_envio.putExtra("idviaje", this.idviaje);
	intent_envio.putExtra("interfaz", this.interfaz);
//	intent_envio.putExtra("idchofer", this.idchofer);
	sendBroadcast(intent_envio);
};

public void login() {
Log.d("Ventana", "login");
intent_envio.putExtra("user", this.user);
intent_envio.putExtra("pass", this.pass);
intent_envio.putExtra("interfaz", this.interfaz);
sendBroadcast(intent_envio);
}

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
      	updateUI(intent);       
      }
  };    
 
  private void recepcionlogin(){
  if (!this.idchofer.equals("CHOFER NO ENCONTRADO"))  {   
	  setInterfaz("activo");
	  final TextView textViewToChange = (TextView) findViewById(R.id.invalido);
	  textViewToChange.setText("");
      final LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      // inflater
      lLayout =(LinearLayout)findViewById(R.id.layout1);
	  //Borro lo que tenga dentro
      lLayout.removeAllViews();
      //Inflo la LinearLoyout
      LinearLayout contentView = (LinearLayout) inflater.inflate(R.layout.activo, null, false);
      //La agrego al linear layout
      lLayout.addView(contentView);
      final TextView textViewToChange2 = (TextView) findViewById(R.id.saludo);
		textViewToChange2.setText("Hola "+ getUser());
      }
  else{
      final TextView textViewToChange = (TextView) findViewById(R.id.invalido);
	  textViewToChange.setText("Login invalido");
      }
  actualiza();
} 


  @Override
	public void onResume() {
		super.onResume();		
        creacion();
	}
	
	@Override
	public void onPause() {
		try{Toast.makeText(this, "Has salido del sistema",
			Toast.LENGTH_SHORT).show();
		    
			try{handler.removeCallbacks(senUpdatesService);} catch (Exception e) { Log.i("ventana pause","sali handler");}
			try{unregisterReceiver(broadcastReceiver); } catch (Exception e) { Log.i("ventana pause","sali receiber");}
			try{stopService(this.intent_recibo);} catch (Exception e) { Log.i("ventana pause","sali stop");} 		
			try{super.onPause();} catch (Exception e) {Log.i("ventana pause","sali super.onpause"); }
			}
		catch (Exception e) { Log.i("ventana","sali por la pausa");} 
	}
 
  @Override
	public void onStop() {
	    Toast.makeText(this, "Has salido del sistema",
		Toast.LENGTH_SHORT).show();
		try{handler.removeCallbacks(senUpdatesService);} catch (Exception e) { Log.i("ventana stop","sali handler");}
		try{unregisterReceiver(broadcastReceiver); } catch (Exception e) { Log.i("ventana stop","sali receiber");}
		try{stopService(this.intent_recibo);} catch (Exception e) { Log.i("ventana stop","sali stop");} 		
		try{super.onStop();} catch (Exception e) {Log.i("ventana stop","sali super.onstop"); }
	}

public void creacion(){
    try {
    this.interfaz="no login";	
    setContentView(R.layout.main);
    final LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout b = (LinearLayout)inflater.inflate(R.layout.login,null);
    lLayout = (LinearLayout)findViewById(R.id.layout1);
    lLayout.addView(b);
    //Inicio el servicio de geolocalizacion
    this.intent_recibo = new Intent(this,ServicioGPS.class);
    this.intent_envio  = new Intent(BROADCAST_ACTION);	
    startService(this.intent_recibo);
    registerReceiver(broadcastReceiver, new IntentFilter(ServicioGPS.BROADCAST_ACTION));
    handler.removeCallbacks(senUpdatesService);
    handler.postDelayed(senUpdatesService, 2000); // 2 second.
  }
    catch (Exception e) { Log.i("ventana","sali oncreate");} 
}  

	public String getUser() {
		return user;
	}

public void setUser(String user) {
		this.user = user;
	}

public String getPass() {
		return pass;
	}

public void setPass(String pass) {
		this.pass = pass;
	}
  
public static String getIP() {
	return IP;
}

public static String getURL_CENTRAL() {
	return URL_CENTRAL;
}

public LinearLayout getlLayout() {
	return lLayout;
}

public void setIdchofer(String idchofer) {
	this.idchofer = idchofer;
}

public String getIdchofer() {
	return idchofer;
}

public String getIdviaje() {
	return idviaje;
}

public String getEstado_chofer() {
	return estadochofer;
}

public String getEstado_viaje() {
	return estadoviaje;
}

public static String getBroadcastAction() {
	return BROADCAST_ACTION;
}

public BroadcastReceiver getBroadcastReceiver() {
	return broadcastReceiver;
}

public void setIdviaje(String idviaje) {
	this.idviaje = idviaje;
}

	
}
 